<template>

  <!--搜索表单-->
  <div style="margin-left: 20px; margin-top: 20px">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="品牌名称">
        <el-input v-model="searchObj.name" placeholder="请输入品牌名称" clearable/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :icon="Search" @click="initData">搜索</el-button>
        <el-button :icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!--按钮组-->
  <div style="margin-left: 20px;margin-top: 10px">
    <el-button size="small" type="primary" plain :icon="Plus" @click="handleShowDialog"
               v-hasPermi="['product:brand:add']">新增
    </el-button>
    <!--    <el-button size="small" type="success" plain :icon="Edit">修改</el-button>-->
    <el-button size="small" type="danger" plain :icon="Delete" @click="handleDel"
               v-hasPermi="['product:brand:remove']">批量删除
    </el-button>
  </div>

  <!--数据表格-->
  <div style="margin-left: 20px;margin-top: 10px">
    <el-table
        style="width: 100%"
        :data="brands"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="品牌名称" property="name" width="180"/>
      <el-table-column label="品牌图标" property="logo">
        <template #default="scope">
          <img :src="scope.row.logo" alt="" style="width: 40px;height: 40px">
        </template>
      </el-table-column>
      <el-table-column label="创建时间" property="createTime"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleShowEditDialog(scope.row)"
                     v-hasPermi="['product:brand:edit']">
            修改
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)" v-hasPermi="['product:brand:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--使用若依的自己封装的分页导航组件-->
    <pagination
        v-show="searchObj.total > 0"
        :total="searchObj.total"
        v-model:page="searchObj.pageNum"
        v-model:limit="searchObj.pageSize"
        @pagination="initData">
    </pagination>
  </div>

  <!-- 新增/更新品牌的对话框 -->
  <div>
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
      <el-form>
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="brand.name" placeholder="请输入品牌名称" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="品牌图标" :label-width="formLabelWidth" prop="logo">
          <el-upload
              class="avatar-uploader"
              :action="uploadPath"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :headers="{Authorization: getToken()}"
          >
            <img v-if="brand.logo" :src="brand.logo" class="avatar">
            <el-icon v-else class="avatar-upload-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSaveOrUpdate">确定</el-button>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import Pagination from "@/components/Pagination/index.vue";
import {listBrands, delBrands, addBrand, getBrand, updateBrand} from "@/api/product/brand.js";
import {onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
//管理登录状态的
import {getToken} from "@/utils/auth";
//数据表格  修改按钮事件函数  先查询数据回显 在弹出更新对话框
const handleShowEditDialog = async (row) => {
  const {data} = await getBrand(row.id)
  brand.value = data
  dialogTitle.value = "更新品牌"
  //弹出对话框
  dialogFormVisible.value = true
}

//新增更新对话框提交按钮的时间函数  要区分新增还是更新
const handleSaveOrUpdate = async () => {
  if (brand.value.id) {
    //更新
    await updateBrand(brand.value)
  } else {
    //新增
    await addBrand(brand.value)
  }
  ElMessage.success("保存成功")
  initData()
  dialogFormVisible.value = false
}

//按钮组：新增按钮事件函数  弹出新增对话框
const handleShowDialog = () => {
  brand.value = {}
  dialogFormVisible.value = true
  dialogTitle.value = "新增品牌"
}

//更新对话框属性和函数
const dialogFormVisible = ref(false)  //默认隐藏对话框
const dialogTitle = ref("新增品牌")
const formLabelWidth = "120px"
const brand = ref({})
const uploadPath = "http://localhost:8080/file/upload"
//文件上传成功的问题
const handleUploadSuccess = (response) => { //参数代表响应的保温数据
  //上传时必须配置 令牌才可以
  // console.log(response, response.data)
  brand.value.logo = response.data.url
  ElMessage.success("上传成功")

}
//文件上传前的回调
const beforeUpload = (rawFile) => {
  console.log(rawFile.type)
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error("请上传jpg和png格式的图片")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('品牌图标大小不能超过 2MB')
    return false
  }
  return true
}
//提交按钮事件函数  新增品牌
const handleSave = async () => {
  await addBrand(brand.value)
  initData()
  dialogFormVisible.value = false
}

//========================新增结束


//定义一个搜索对象  接收搜索条件
const searchObj = ref({
  name: null,
  pageNum: 1,
  pageSize: 3,
  total: 0
})


const brands = ref([])
const selection = ref([])
//批量删除按钮事件函数
const handleDel = async () => {
  //数据校验 如果不选中行不提交删除请求
  if (!selection.value || selection.value.length === 0) {
    ElMessage.error("请选择要删除的行")
    return
  }

  ElMessageBox.confirm("确定删除吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {

    //1、获取被选中的要删除的id
    let ids = selection.value.map((obj) => {
      return obj.id
    }).join(",");

    //2、提交批量删除的请求
    await delBrands(ids)
    //3、刷新页面数据
    ElMessage.success(`删除 ${selection.value.map((obj) => {
      return obj.name
    }).join(",")} 成功`)
    initData()

  }).catch(() => {
  })

}

//表格的行选中发生的事件函数
const handleSelectionChange = (newSelection) => {
  selection.value = newSelection
}


//页面初始化，加载分页数据展示
onMounted(() => {
  //vue的钩子函数  页面渲染前执行
  //调用加载数据的函数
  initData()
})

const initData = async () => {
  const {total, rows} = await listBrands(searchObj.value)
   searchObj.value.total = +total
  brands.value = rows
}

//重置按钮事件函数：  清空查询条件  加载默认数据界面
const handleReset = () => {
  searchObj.value = {
    name: null,
    pageNum: 1,
    pageSize: 3,
    total: 0
  }
  initData()
}

//数据表格删除按钮事件函数
const handleDelete = async (row) => {
  await delBrands(row.id)
  ElMessage.success("删除成功")
  initData()
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>